import './main.js'
import $ from 'jquery';
import 'bootstrap-datepicker'
import { ActuatorService } from './api/actuator'
import { SearchBarComponent } from '/src/components/component/searchbar/searchbarcomponent.js'
import { ChartComponent } from '/src/components/component/chart/chartcomponent.js'
import { openTableModal, openSearchBarModal } from '/src/components/modal/modal.js'
import { NotificationManager } from '/src/util/notification/notification.js'
import { DOMUtils } from '/src/util/dom/dom.js'
import { createConfig } from '/src/util/config/baseconfig.js';

// ==================== 常量配置 ====================
const INDEX_EXTENSION = {
    SELECTORS: {
        EXECUTE: '#execute',
        CLEAR: '#clear',
        ADD: '#add',
        SAVE: '#save',
        SWITCH_PAGE: '#switchPage',
        ACTUATOR_SELECT: '#actuatorModelSelected',
        TYPE: '#type',
        VALUE: '#value',
        DATA_SOURCE: '#dataSource',
        CHART_NAME: '#chartName',
        TEMP_CHART: '#tempChart',
        SEARCH_BAR: '#searchBar',
        SQL: '#sql',
        BASE_CONFIG: '#baseConfigContainer',
        SERIES_CONFIG: '#seriesConfigContainer',
        TIME: '#time'
    }
};

const CONFIG = createConfig(INDEX_EXTENSION);

// ==================== 状态管理 ====================
const AppState = {
    sql: '',
    searchBarComponent: null,
    chartComponent: null,
    actuatorModels: new Map(), // 使用Map存储完整的模型数据
    
    // 状态更新方法
    setSql(value) {
        this.sql = value;
    },
    
    setSearchBarComponent(component) {
        this.searchBarComponent = component;
    },
    
    setChartComponent(component) {
        this.chartComponent = component;
    },
    
    addActuatorModel(id, data) {
        this.actuatorModels.set(id, data);
    },
    
    getActuatorModel(id) {
        return this.actuatorModels.get(parseInt(id));
    },
    
    clearActuatorModels() {
        this.actuatorModels.clear();
    },
    
    reset() {
        this.sql = '';
        this.searchBarComponent = null;
        this.chartComponent = null;
        this.actuatorModels.clear();
    }
};

// ==================== 选择器管理模块 ====================
const SelectManager = {
    init() {
        this.clearSelect();
        this.addDefaultOption();
        this.loadActuatorModels();
    },
    
    clearSelect() {
        const select = document.getElementById('actuatorModelSelected');
        if (select) {
            select.innerHTML = '';
            AppState.clearActuatorModels();
        }
    },
    
    addDefaultOption() {
        const select = document.getElementById('actuatorModelSelected');
        if (!select) return;
        
        const defaultOption = new Option('自定义', CONFIG.CHART_TYPES.CUSTOM);
        defaultOption.selected = true;
        select.add(defaultOption);
    },
    
    async loadActuatorModels() {
        try {
            const res = await ActuatorService.loadActuatorModel();
            if (res) {
                res.forEach(item => this.createOptionElement(item));
            }
        } catch (error) {
            console.error('Failed to load actuator model:', error);
            NotificationManager.error(CONFIG.MESSAGES.LOAD_MODEL_FAILED);
        }
    },
    
    createOptionElement(item) {
        const select = document.getElementById('actuatorModelSelected');
        if (!select) return;
        
        const hasSignature = item['methodSignature']?.trim();
        const option = document.createElement('option');
        const id = item['id'];

        // 简化：只存储id到option的value
        option.value = id;
        option.textContent = item['name'] || CONFIG.MESSAGES.UNKNOWN_NAME;
        
        // 将完整数据存储到AppState中
        AppState.addActuatorModel(id, {
            id: id,
            name: item['name'],
            sql: item['sql'],
            methodSignature: item['methodSignature'],
            searchBar: item['searchBar'],
            chartType: item['chartType'],
            dataSource: item['dataSource'],
            type: hasSignature ? CONFIG.CHART_TYPES.SIGNATURE : CONFIG.CHART_TYPES.SQL,
            value: hasSignature || item['sql'] || ''
        });
        
        select.appendChild(option);
    },
    
    getSelectedData() {
        const selectedValue = DOMUtils.getValue(CONFIG.SELECTORS.ACTUATOR_SELECT);

        if (selectedValue === CONFIG.CHART_TYPES.CUSTOM) {
            return { isCustom: true, value: CONFIG.CHART_TYPES.CUSTOM };
        }
        const data = AppState.getActuatorModel(selectedValue);
        return data ? { isCustom: false, ...data } : null;
    }
};

// ==================== 事件处理模块 ====================
const EventHandlers = {
    init() {
        this.bindEvents();
    },
    
    bindEvents() {
        const events = [
            { selector: CONFIG.SELECTORS.EXECUTE, handler: this.handleExecute },
            { selector: CONFIG.SELECTORS.CLEAR, handler: this.handleClear },
            { selector: CONFIG.SELECTORS.ADD, handler: this.handleAdd },
            { selector: CONFIG.SELECTORS.SAVE, handler: this.handleSave },
            { selector: CONFIG.SELECTORS.SWITCH_PAGE, handler: this.handleSwitchPage },
            { selector: CONFIG.SELECTORS.ACTUATOR_SELECT, handler: this.handleSelectChange, event: 'change' }
        ];
        
        events.forEach(({ selector, handler, event = 'click' }) => {
            $(selector).on(event, handler.bind(this));
        });
    },
    
    handleSelectChange() {
        const selectedData = SelectManager.getSelectedData();
        if (selectedData?.isCustom) {
            this.resetCustomMode();
        } else if (selectedData) {
            this.setSelectedMode(selectedData);
        }
        
        this.handleClear();
        SearchBarManager.generate(selectedData?.searchBar);
    },
    
    resetCustomMode() {
        DOMUtils.setValue(CONFIG.SELECTORS.TYPE, '');
        DOMUtils.setProperty(CONFIG.SELECTORS.TYPE, 'disabled', false);
        DOMUtils.setValue(CONFIG.SELECTORS.VALUE, '');
    },
    
    setSelectedMode(data) {
        DOMUtils.setValue(CONFIG.SELECTORS.TYPE, data.type);
        DOMUtils.setProperty(CONFIG.SELECTORS.TYPE, 'disabled', true);
        DOMUtils.setValue(CONFIG.SELECTORS.VALUE, data.value);
    },
    
    handleSwitchPage() {
        window.location.href = '/src/page/layout/layout.html';
    },
    
    async handleExecute() {
        const selectedData = SelectManager.getSelectedData();
        const dataSource = DOMUtils.getValue(CONFIG.SELECTORS.DATA_SOURCE);
        const time = DOMUtils.getValue(CONFIG.SELECTORS.TIME);

        try {
            // 优先处理自定义SQL
            if (AppState.sql) {
                await ChartManager.loadData({
                    text: '',
                    type: CONFIG.CHART_TYPES.SQL,
                    value: AppState.sql,
                    dataSource,
                    time
                });
                return;
            }
            
            // 处理手动输入的值
            const value = DOMUtils.getValue(CONFIG.SELECTORS.VALUE);
            if (value && selectedData) {
                await ChartManager.loadData({
                    text: '',
                    type: DOMUtils.getValue(CONFIG.SELECTORS.TYPE),
                    value,
                    dataSource,
                    time
                });
                return;
            }
            
            // 处理自定义模式
            if (selectedData?.isCustom) {
                this.openCustomTableModal(dataSource);
                return;
            }
            
            // 处理保存的图表
            if (selectedData?.id) {
                await this.loadSavedChart(selectedData.id);
            }
        } catch (error) {
            console.error('Execute failed:', error);
            NotificationManager.error(CONFIG.MESSAGES.EXECUTE_FAILED);
        }
    },
    
    openCustomTableModal(dataSource) {
        openTableModal((returnData) => {
            SearchBarManager.generate(returnData['searchBar']);
            AppState.setSql(returnData['sql']);
            DOMUtils.show(CONFIG.SELECTORS.CLEAR);
            ChartManager.loadData({
                text: '',
                type: CONFIG.CHART_TYPES.SQL,
                value: returnData['sql'],
                dataSource,
                time: parseInt(DOMUtils.getValue(CONFIG.SELECTORS.TIME))
            });
        });
    },
    
    async loadSavedChart(id) {
        try {
            const res = await ActuatorService.getById({ id });
            if (res) {
                const data = res;
                await ChartManager.loadData({
                    id: data.id,
                    text: data.name,
                    value: data.sql || data.methodSignature,
                    type: data.sql ? CONFIG.CHART_TYPES.SQL : CONFIG.CHART_TYPES.SIGNATURE,
                    chartType: data.ChartType,
                    dataSource: data.DataSource,
                    time: parseInt(DOMUtils.getValue(CONFIG.SELECTORS.TIME))
                });
            }
        } catch (error) {
            console.error('Failed to load saved chart:', error);
            NotificationManager.error(CONFIG.MESSAGES.LOAD_CHART_FAILED);
        }
    },
    
    handleAdd() {
        openSearchBarModal((returnData) => {
            try {
                SearchBarManager.addComponent(returnData['searchBar']);
                NotificationManager.success(CONFIG.MESSAGES.ADD_SUCCESS);
            } catch (error) {
                console.error('Failed to add component:', error);
                NotificationManager.error(CONFIG.MESSAGES.ADD_FAILED);
            }
        });
    },
    
    async handleSave() {
        const selectedData = SelectManager.getSelectedData();
        const chartName = DOMUtils.getValue(CONFIG.SELECTORS.CHART_NAME);
        
        if (!this.validateSaveInputs(chartName)) {
            return;
        }
        
        try {
            const config = AppState.chartComponent?.configInstance?.getConfigData(AppState.chartComponent.chart);
            const saveData = this.prepareSaveData(selectedData, chartName, config);
            await ActuatorService.saveActuator(saveData);
            NotificationManager.success(CONFIG.MESSAGES.SAVE_SUCCESS);
        } catch (error) {
            console.error('Save failed:', error);
            NotificationManager.error(CONFIG.MESSAGES.SAVE_FAILED);
        }
    },
    
    validateSaveInputs(chartName) {
        if (!chartName?.trim()) {
            NotificationManager.error(CONFIG.MESSAGES.CHART_NAME_REQUIRED);
            return false;
        }
        
        if (DOMUtils.isEmpty(CONFIG.SELECTORS.TEMP_CHART)) {
            NotificationManager.error(CONFIG.MESSAGES.EXECUTE_CHART_REQUIRED);
            return false;
        }
        
        return true;
    },
    
    prepareSaveData(selectedData, chartName, config) {
        const type = DOMUtils.getValue(CONFIG.SELECTORS.TYPE);
        const value = DOMUtils.getValue(CONFIG.SELECTORS.VALUE);
        
        return {
            id: selectedData?.id,
            name: chartName,
            sql: type === CONFIG.CHART_TYPES.SQL ? value : '',
            methodSignature: type === CONFIG.CHART_TYPES.SIGNATURE ? value : '',
            searchBar: SearchBarManager.getConfigData(),
            config: JSON.stringify(config),
            chartType: AppState.chartComponent?.currentType,
            dataSource: DOMUtils.getValue(CONFIG.SELECTORS.DATA_SOURCE),
            time: parseInt(DOMUtils.getValue(CONFIG.SELECTORS.TIME))
        };
    },
    
    handleClear() {
        AppState.setSql('');
        DOMUtils.setValue(CONFIG.SELECTORS.SQL, '');
        DOMUtils.hide(CONFIG.SELECTORS.CLEAR);
        DOMUtils.empty(CONFIG.SELECTORS.BASE_CONFIG);
        DOMUtils.empty(CONFIG.SELECTORS.SERIES_CONFIG);
        
        ChartManager.destroy();
        SearchBarManager.clear();
    }
};

// ==================== 搜索栏管理模块 ====================
const SearchBarManager = {
    generate(searchBar) {
        this.destroy();
        
        if (searchBar) {
            AppState.setSearchBarComponent(new SearchBarComponent(CONFIG.SELECTORS.SEARCH_BAR, {
                config: searchBar
            }));
            AppState.searchBarComponent.init();
        }
    },
    
    addComponent(searchBarConfig) {
        if (AppState.searchBarComponent) {
            AppState.searchBarComponent.addComponent(searchBarConfig);
        } else {
            AppState.setSearchBarComponent(new SearchBarComponent(CONFIG.SELECTORS.SEARCH_BAR, {
                config: searchBarConfig
            }));
            AppState.searchBarComponent.init();
        }
    },
    
    getConfigData() {
        return AppState.searchBarComponent?.getSearchConfigData() || null;
    },
    
    clear() {
        if (AppState.searchBarComponent) {
            AppState.searchBarComponent.clear();
        }
    },
    
    destroy() {
        if (AppState.searchBarComponent) {
            AppState.searchBarComponent.destroy();
            AppState.setSearchBarComponent(null);
        }
    }
};

// ==================== 图表管理模块 ====================
const ChartManager = {
    async loadData(sourceData) {
        try {
            this.destroy();
            
            AppState.setChartComponent(new ChartComponent($(CONFIG.SELECTORS.TEMP_CHART), {
                showToolbox: true,
                name: 'tempChart',
                searchBarComponent: AppState.searchBarComponent,
                sourceData: sourceData,
                chartType: sourceData.chartType,
                dataSource: sourceData.dataSource,
                time: sourceData.TIME
            }));
            
            AppState.chartComponent.on('dataLoaded', () => {
                AppState.chartComponent.generateConfigForm();
            });
            
            await AppState.chartComponent.loadData(sourceData);
        } catch (error) {
            console.error('Failed to load chart data:', error);
            NotificationManager.error(CONFIG.MESSAGES.LOAD_CHART_DATA_FAILED);
        }
    },
    
    destroy() {
        if (AppState.chartComponent) {
            AppState.chartComponent.destroy();
            AppState.setChartComponent(null);
        }
    }
};

// ==================== 应用初始化模块 ====================
const App = {
    init() {
        this.initUI();
        this.initModules();
    },
    
    initUI() {
        DOMUtils.hide(CONFIG.SELECTORS.CLEAR);
    },
    
    initModules() {
        SelectManager.init();
        EventHandlers.init();
    }
};

// ==================== 应用启动 ====================
$(function () {
    App.init();
});